package com.example.thread.demo.alternate.print6;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author zhy
 * @version 1.0.0
 * @ClassName Solution.java
 * @Description TODO
 * @createTime 2020年11月10日 00:02:00
 */
public class Solution {

    private Lock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();
    private int i = 1;
    private Object objLock = new Object();

    class Print implements Runnable {
        @Override
        public void run() {
            while (true) {
                try {
                    lock.lock();
                    condition.signal();
                    if (i <= 100) {
                        System.out.println(Thread.currentThread().getName() + "--->" + i);
                        i++;
                    } else {
                        break;
                    }
                    condition.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }
            }
        }
    }

    class Print2 implements Runnable {
        @Override
        public void run() {
            while (true) {
                synchronized (objLock) {
                    objLock.notify();
                    if (i <= 100) {
                        System.out.println(Thread.currentThread().getName() + "--->" + i);
                        i++;
                    } else {
                        break;
                    }
                    try {
                        objLock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
//        new Thread(solution.new Print()).start();
//        new Thread(solution.new Print()).start();
        new Thread(solution.new Print2()).start();
        new Thread(solution.new Print2()).start();
    }
}
